package com.example.cms.Departments;

import com.example.cms.DB.DBUtil;
import com.example.cms.Doctors.Doctor;
import com.example.cms.Doctors.DoctorsManager;
import java.sql.*;
import java.util.*;
public class DepartmentsManager
{
    private Scanner scanner;
    private DoctorsManager doctorsManager;
    public DepartmentsManager(){
        this.scanner = new Scanner(System.in);
    }
    // ==================== 科室管理 ====================
    public void showDepartmentMenu() {
        while (true) {
            System.out.println("\n--- 科室管理 ---");
            System.out.println("1. 添加科室");
            System.out.println("2. 查看科室信息");
            System.out.println("3. 修改科室信息");
            System.out.println("4. 查看科室列表");
            System.out.println("5. 设置科室医生");
            System.out.println("0. 返回主菜单");

            System.out.print("请选择操作: ");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    addDepartment();
                    break;
                case "2":
                    viewDepartment();
                    break;
                case "3":
                    updateDepartment();
                    break;
                case "4":
                    listDepartments();
                    break;
                case "5":
                    setDepartmentDoctors();
                    break;
                case "0":
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void addDepartment() {
        System.out.println("\n--- 添加科室 ---");
        try {
            System.out.print("科室代码: ");
            String deptCode = scanner.nextLine();

            System.out.print("科室名称: ");
            String deptName = scanner.nextLine();

            System.out.print("科室描述: ");
            String description = scanner.nextLine();

            System.out.print("位置: ");
            String location = scanner.nextLine();

            System.out.print("联系电话: ");
            String phone = scanner.nextLine();

            Department department = new Department(deptCode, deptName, description);
            department.setLocation(location);
            department.setPhone(phone);

            if (addDepartmentToDB(department)) {
                System.out.println("科室添加成功！");
            } else {
                System.out.println("科室添加失败！");
            }
        } catch (Exception e) {
            System.out.println("添加失败: " + e.getMessage());
        }
    }

    private void viewDepartment() {
        System.out.println("\n--- 查看科室信息 ---");
        System.out.print("请输入科室ID: ");
        String input = scanner.nextLine();

        try {
            Department department = findDepartmentById(Integer.parseInt(input));

            if (department != null) {
                displayDepartmentInfo(department);
            } else {
                System.out.println("未找到科室信息！");
            }
        } catch (Exception e) {
            System.out.println("查询失败: " + e.getMessage());
        }
    }

    private void updateDepartment() {
        System.out.println("\n--- 修改科室信息 ---");
        System.out.print("请输入科室ID: ");
        int departmentId = Integer.parseInt(scanner.nextLine());

        try {
            Department department = findDepartmentById(departmentId);
            if (department == null) {
                System.out.println("科室不存在！");
                return;
            }

            displayDepartmentInfo(department);
            System.out.println("\n请输入要修改的信息(留空保持不变):");

            System.out.print("科室名称[" + department.getDeptName() + "]: ");
            String deptName = scanner.nextLine();
            if (!deptName.isEmpty()) department.setDeptName(deptName);

            System.out.print("科室描述[" + department.getDescription() + "]: ");
            String description = scanner.nextLine();
            if (!description.isEmpty()) department.setDescription(description);

            System.out.print("位置[" + department.getLocation() + "]: ");
            String location = scanner.nextLine();
            if (!location.isEmpty()) department.setLocation(location);

            System.out.print("联系电话[" + department.getPhone() + "]: ");
            String phone = scanner.nextLine();
            if (!phone.isEmpty()) department.setPhone(phone);

            if (updateDepartmentInDB(department)) {
                System.out.println("科室信息更新成功！");
            } else {
                System.out.println("科室信息更新失败！");
            }
        } catch (Exception e) {
            System.out.println("修改失败: " + e.getMessage());
        }
    }

    private void listDepartments() {
        System.out.println("\n--- 科室列表 ---");
        try {
            List<Department> departments = getAllDepartments();
            if (departments.isEmpty()) {
                System.out.println("暂无科室数据");
                return;
            }

            System.out.println("ID\t代码\t名称\t位置\t状态");
            System.out.println("----------------------------------------");
            for (Department department : departments) {
                System.out.printf("%d\t%s\t%s\t%s\t%s\n",
                        department.getDepartmentId(),
                        department.getDeptCode(),
                        department.getDeptName(),
                        department.getLocation(),
                        department.getStatus());
            }
        } catch (Exception e) {
            System.out.println("获取科室列表失败: " + e.getMessage());
        }
    }

    private void setDepartmentDoctors() {
        System.out.println("\n--- 设置科室医生 ---");
        System.out.print("请输入科室ID: ");
        int departmentId = Integer.parseInt(scanner.nextLine());

        try {
            Department department = findDepartmentById(departmentId);
            if (department == null) {
                System.out.println("科室不存在！");
                return;
            }

            // 显示当前科室的医生
            List<Doctor> currentDoctors = getDoctorsByDepartment(departmentId);
            System.out.println("\n当前科室医生:");
            if (currentDoctors.isEmpty()) {
                System.out.println("暂无医生");
            } else {
                for (Doctor doctor : currentDoctors) {
                    System.out.printf("%d - %s (%s)\n", doctor.getDoctorId(), doctor.getName(), doctor.getTitle());
                }
            }

        } catch (Exception e) {
            System.out.println("设置失败: " + e.getMessage());
        }
    }


    private void displayDepartmentInfo(Department department) {
        System.out.println("\n=== 科室信息 ===");
        System.out.println("科室ID: " + department.getDepartmentId());
        System.out.println("科室代码: " + department.getDeptCode());
        System.out.println("科室名称: " + department.getDeptName());
        System.out.println("科室描述: " + department.getDescription());
        System.out.println("位置: " + department.getLocation());
        System.out.println("联系电话: " + department.getPhone());
        System.out.println("状态: " + department.getStatus());
    }

    // 科室相关操作方法
    private boolean addDepartmentToDB(Department department) {
        String sql = "INSERT INTO departments (dept_code, dept_name, description, location, phone) " +
                "VALUES (?, ?, ?, ?, ?)";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setString(1, department.getDeptCode());
            pstmt.setString(2, department.getDeptName());
            pstmt.setString(3, department.getDescription());
            pstmt.setString(4, department.getLocation());
            pstmt.setString(5, department.getPhone());

            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                try (ResultSet rs = pstmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        department.setDepartmentId(rs.getInt(1));
                    }
                }
                return true;
            }
        } catch (SQLException e) {
            System.err.println("添加科室失败: " + e.getMessage());
        }
        return false;
    }

    private Department findDepartmentById(int departmentId) {
        String sql = "SELECT * FROM departments WHERE department_id = ?";

        try (   Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, departmentId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return mapResultSetToDepartment(rs);
                }
            }
        } catch (SQLException e) {
            System.err.println("查询科室失败: " + e.getMessage());
        }
        return null;
    }

    private boolean updateDepartmentInDB(Department department) {
        String sql = "UPDATE departments SET dept_code = ?, dept_name = ?, description = ?, " +
                "location = ?, phone = ? WHERE department_id = ?";

        try (   Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, department.getDeptCode());
            pstmt.setString(2, department.getDeptName());
            pstmt.setString(3, department.getDescription());
            pstmt.setString(4, department.getLocation());
            pstmt.setString(5, department.getPhone());
            pstmt.setInt(6, department.getDepartmentId());

            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            System.err.println("更新科室失败: " + e.getMessage());
        }
        return false;
    }

    private List<Department> getAllDepartments() {
        List<Department> departments = new ArrayList<>();
        String sql = "SELECT * FROM departments ORDER BY create_time DESC";

        try (   Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                departments.add(mapResultSetToDepartment(rs));
            }
        } catch (SQLException e) {
            System.err.println("获取所有科室失败: " + e.getMessage());
        }
        return departments;
    }

    private List<Doctor> getDoctorsByDepartment(int departmentId) {
        List<Doctor> doctors = new ArrayList<>();
        String sql = "SELECT d.*, dept.dept_name FROM doctors d " +
                "LEFT JOIN departments dept ON d.department_id = dept.department_id " +
                "WHERE d.department_id = ? AND d.status = 'ACTIVE' " +
                "ORDER BY d.create_time DESC";

        try (   Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, departmentId);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    doctors.add(doctorsManager.mapResultSetToDoctor(rs));
                }
            }
        } catch (SQLException e) {
            System.err.println("获取科室医生失败: " + e.getMessage());
        }
        return doctors;

    }

    private Department mapResultSetToDepartment(ResultSet rs) throws SQLException {
        Department department = new Department();
        department.setDepartmentId(rs.getInt("department_id"));
        department.setDeptCode(rs.getString("dept_code"));
        department.setDeptName(rs.getString("dept_name"));
        department.setDescription(rs.getString("description"));
        department.setLocation(rs.getString("location"));
        department.setPhone(rs.getString("phone"));
        department.setStatus(rs.getString("status"));
        return department;
    }

    public void setDoctorsManager(DoctorsManager doctorsManager) {
        this.doctorsManager = doctorsManager;
    }

}
